package energy_conf

import (
	"context"
	"fmt"
	model "service/model/crm_base"
	mCache "service/model/hr_cache"
	"strconv"

	gpb "gitee.com/cloudapex/protos/crm_base/pb"
	gupb "gitee.com/cloudapex/protos/hr_cache/pb"
	"gitee.com/cloudapex/ulern/htp"
	"gitee.com/cloudapex/ulern/util"
	"github.com/gin-gonic/gin"

	"service/model/mod"
)

/*
 * 描述:业务项目配置列表
 * 路由: energy/fraProjConfList
 * 方法: POST
 *********************************************************************/
type FraProjConfList struct {
	mod.SortFinder
	mod.PageFinder

	Type    int64  `form:"type" json:"type"  binding:"required,min=1,max=2"` //type 1.取军团配置列表 2 取个人配置列表
	StrShow string `form:"strShow" json:"strShow,omitempty"`                 //组织架构string
	//  表中数据
	UId   int64  `form:"uId" json:"uId,omitempty"`     //用户ID
	SShow uint64 `form:"sShow" json:"sShow,omitempty"` //组织架构
}

// 说明：项目配置列表 出参
type FraProConfigRes struct {
	Id        int64           `form:"id" json:"id"`               //自增ID
	CId       int64           `form:"cId" json:"cId"`             //公司id
	UId       int64           `form:"uId" json:"uId"`             //用户ID
	SShow     uint64          `form:"sShow" json:"sShow"`         //组织架构
	StrShow   string          `form:"strShow" json:"strShow"`     //组织架构 string类型
	SShowName string          `form:"sShowName" json:"sShowName"` //组织架构名称
	UName     string          `form:"uName" json:"uName"`         //用户名称
	FPList    []FProConfigRes `form:"fPList" json:"fPList"`       //项目列表

}
type FProConfigRes struct {
	Id     int64  `form:"id" json:"id"`         //自增ID
	PId    int64  `form:"pId" json:"pId"`       //项目id
	PName  string `form:"pName" json:"pName"`   //项目名称
	ConId  int64  `form:"conId" json:"conId"`   //base_con 关联ID
	PCount int64  `form:"pCount" json:"pCount"` //工作池的数量
	PGet   int64  `form:"pGet" json:"pGet"`     //每日领取数据
}

func (this *FraProjConfList) Handle(c *gin.Context, ctx context.Context) htp.Response {
	jwtUser := mod.CurrUser(c)
	intNum, _ := strconv.Atoi(this.StrShow)
	this.SShow = uint64(intNum)
	//传参
	compyListreq := &gpb.FraInfoReq{
		FraInfo: &gpb.FraProConfig{
			CId:   jwtUser.CId,
			UId:   this.UId,
			SShow: this.SShow,
		},
		Type:    this.Type,
		Page:    int64(this.Page),
		Count:   int64(this.Pnum),
		DesClum: int64(this.Order),
		IsDes:   int64(this.Orule + 1),
	}
	list, err := model.FraProjConf.GetFraConfigList(ctx, compyListreq)
	if list == nil || nil != err {
		return htp.RespParamErr("", err)
	}

	//映射
	items := []*FraProConfigRes{}
	if err := util.Convert(&items, list.FraConf); err != nil {
		return htp.RespConvertErr("", err)
	}
	//  设置参数
	this.SetParamList(c, ctx, items)
	if err != nil {
		return htp.RespModelErr("", err)
	}
	for _, v := range items {

		v.StrShow = fmt.Sprintf("%d", v.SShow)
	}

	return htp.RespOK("", &struct {
		Total int64       `json:"total"`
		List  interface{} `json:"list"`
	}{list.Count, items})

}

/*
* 描述: 业务项目配置添加
* 路由: /crm/energy/addFraProjConf
* 方法: POST
*********************************************************************/
type AddFraProjConf struct {
	PId    int64 `form:"pId" json:"pId"  binding:"required"`       //-- 项目id
	ConId  int64 `form:"conId" json:"conId"  binding:"required"`   //--  base_con 关联ID
	PCount int64 `form:"pCount" json:"pCount"  binding:"required"` //	-- 工作池的数量
	PGet   int64 `form:"pGet" json:"pGet"  binding:"required"`     //	-- 每日领取数据
}

func (this *AddFraProjConf) Handle(c *gin.Context, ctx context.Context) htp.Response {
	req := &gpb.FProConfig{
		PId:    this.PId,
		ConId:  this.ConId,
		PCount: this.PCount,
		PGet:   this.PGet,
	}
	_, err := model.FraProjConf.EditFraProConfig(ctx, req)
	if err != nil {
		return htp.RespModelErr("", err)
	}
	return htp.RespOK("", "")
}

/*
* 描述: 业务项目配置删除
* 路由: /crm/energy/delcFraProjConf
* 方法: POST
*********************************************************************/
type DelcFraProjConf struct {
	Id int64 `form:"id" json:"id"  binding:"required"` //id
}

func (this *DelcFraProjConf) Handle(c *gin.Context, ctx context.Context) htp.Response {
	req := &gpb.FProConfig{
		Id: this.Id,
	}
	_, err := model.FraProjConf.DelectFraProConfig(ctx, req)
	if err != nil {
		return htp.RespModelErr("", err)
	}
	return htp.RespOK("", "")
}

//**********************************************method*************************************************************

//	设置参数
func (this *FraProjConfList) SetParamList(c *gin.Context, ctx context.Context, res []*FraProConfigRes) {
	jwtUser := mod.CurrUser(c)
	cId := jwtUser.CId
	ids := make([]int64, 0)
	//  设置组织架构
	this.SetShowList(res, ctx)
	for _, resf := range res {
		ids = append(ids, resf.Id)
	}
	//  设置员工的名字
	this.setUserList(res, ctx, jwtUser.CId)

	//  获取子表数据并填充项目id
	clist := getFPList(ids, ctx, cId)

	//  设置子表的数据
	for i, _ := range res {
		resf := res[i]
		resf.FPList = make([]FProConfigRes, 0)
		//  设置子表的数据
		for j, _ := range clist {
			cresf := clist[j]
			if resf.Id == cresf.ConId {
				resf.FPList = append(resf.FPList, cresf)
			}
		}

		ids = append(ids, resf.Id)
	}

}

func (this *FraProjConfList) SetShowList(res []*FraProConfigRes, ctx context.Context) {

	//  获取去重的值
	s_showids := GetShowIdList(res)
	frawCache := &gupb.FullReqUIdsReq{
		Ids: s_showids,
	}
	frawCacheres, _ := mCache.FrameWorkCache.GetFraNameByShowIdList(ctx, frawCache)

	for i, _ := range res {
		resf := res[i]
		resf.FPList = make([]FProConfigRes, 0)
		//组织架构赋值
		if frawCacheres != nil && len(frawCacheres.FullUList) > 0 {

			for _, vf := range frawCacheres.FullUList {
				if this.Type == 1 {
					if resf.SShow == vf.Id && vf.Name != "" {
						resf.SShowName = vf.Name
					}
				} else {
					if resf.SShow == vf.Id && vf.FullName != "" {
						resf.SShowName = vf.FullName
					}
				}
			}
		}

	}
}

func (this *FraProjConfList) setUserList(res []*FraProConfigRes, ctx context.Context, CId int64) {
	//  获取去重的值
	uidList := GetUidList(res)
	userListRes, _ := mCache.UserCacheServer.UserNameList(ctx, &gupb.UserLoginReqIdsReq{CId: CId, Ids: uidList})

	for i, _ := range res {
		resf := res[i]
		resf.FPList = make([]FProConfigRes, 0)
		//组织架构赋值
		if userListRes != nil && len(userListRes.NameList) > 0 {

			for _, vf := range userListRes.NameList {
				if resf.UId == vf.Id && vf.Name != "" {
					resf.UName = vf.Name
				}
			}
		}

	}
}

//  获取去重的值Uid
func GetUidList(res []*FraProConfigRes) (uidList []int64) {
	for _, v := range res {
		fage := false
		for ssi, _ := range uidList {
			if v.UId == uidList[ssi] {
				fage = true
				break
			}
		}
		if !fage {
			uidList = append(uidList, v.UId)
		}
	}
	return
}

//  获取去重的值
func GetShowIdList(res []*FraProConfigRes) (s_showids []uint64) {
	for _, v := range res {
		fage := false
		for ssi, _ := range s_showids {
			if v.SShow == s_showids[ssi] {
				fage = true
				break
			}
		}
		if !fage {
			s_showids = append(s_showids, v.SShow)
		}
	}
	return
}

//  获取子表数据
func getFPList(ids []int64, ctx context.Context, cId int64) (items []FProConfigRes) {

	craParamsReq := &gpb.FraParaIds{
		Ids: ids,
	}
	clist, err := model.FraProjConf.GetFraParams(ctx, craParamsReq)
	if err != nil || clist.ProConfig == nil || len(clist.ProConfig) == 0 {
		return
	}
	if err := util.Convert(&items, clist.ProConfig); err != nil {
		return
	}
	names, err := model.Proj.GetProjIdNames(ctx, cId)
	for i, _ := range items {
		it := &items[i]
		it.PName = names[it.PId]
	}
	return
}
